// pages/casherDesk/casherDesk.js
//获取应用实例
const app = getApp();
var httpClient = require('../../utils/httpClient.js');
var utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: [],
    totalAmount: {
      value: 0,
      formatValue: "0.00"
    },
    showChangeNumView: false,
    mudDisabled: true,
    bottomNumber: 0,
    currentChangeItem: {},
    payMethod: 1,
    receipts: "",
    giveChange: {
      format: "0.00",
      value: 0
    },
    showPayView: false
  },
  refreshPage: function () {
    this.setData({
      goods: [],
      totalAmount: {
        value: 0,
        formatValue: "0.00"
      },
      showChangeNumView: false,
      mudDisabled: true,
      bottomNumber: 0,
      currentChangeItem: {},
      payMethod: 1,
      receipts: "",
      giveChange: {
        format: "0.00",
        value: 0
      },
      showPayView: false
    });
  },
  /**
   * 格式化
   */
  refreshFormatValue: function () {
    this.data.totalAmount.value = 0;
    var totalAmount = {
      value: 0
    };
    for (var i in this.data.goods) {
      this.data.goods[i].amount = this.data.goods[i].price * this.data.goods[i].number;
      this.data.goods[i].amountFormat = utils.outputmoney(this.data.goods[i].amount);
      var good = this.data.goods[i];
      totalAmount.value = totalAmount.value + good.amount;
    }
    totalAmount.formatValue = utils.outputmoney(totalAmount.value);
    this.setData({
      totalAmount: totalAmount,
      goods: this.data.goods
    });
  },
  scan: function () {
    var that = this;
    wx.scanCode({
      success: (res) => {
        var shopId = wx.getStorageSync("shopId");
        var goodInfo = that.getGoodInfoFromSnap(res.result);
        if (goodInfo != null) {
          that.addGood(goodInfo);
          return;
        }
        httpClient.get('/good/view/' + shopId + '/' + res.result, function (result) {
          that.addGood(result);
        });
      }
    });
  },
  addGood: function (good) {
    //通过id判断是否已存在列表中，不存在则更新
    for (var i in this.data.goods) {
      if (this.data.goods[i].id == good.id) {
        this.data.goods[i].number++;
        this.data.goods[i].amount = this.data.goods[i].price * this.data.goods[i].number;
        this.data.goods[i].amountFormat = utils.outputmoney(this.data.goods[i].amount);
        this.setData({
          goods: this.data.goods
        });
        this.refreshFormatValue();
        return;
      }
    }
    good.priceFormat = utils.outputmoney(good.price);
    good.number = 1;
    good.amount = good.price * good.number;
    good.amountFormat = utils.outputmoney(good.amount);
    this.data.goods.push(good);
    this.setData({
      goods: this.data.goods
    });
    this.refreshFormatValue();
  },
  /**
   * 选择商品数量修改
   */
  bindGoodChange: function (e) {
    var mudDisabled = this.data.mudDisabled;
    if (e.currentTarget.dataset.number < 2) {
      mudDisabled = true;
    } else {
      mudDisabled = false;
    }
    this.setData({
      showChangeNumView: true,
      currentChangeItem: e.currentTarget.dataset,
      mudDisabled: mudDisabled
    });
  },
  /**
   * 结算
   */
  settle: function () {
    if (this.data.totalAmount.value == 0) {
      return;
    }
    this.setData({
      showPayView: true,
    })
  },
  // 取消修改数目
  quitChangeNum: function () {
    this.setData({
      showChangeNumView: false
    });
  },
  // 确定修改数目
  confirmChangeNum: function () {
    var goods = this.data.goods;
    for (var i in goods) {
      if (goods[i].id == this.data.currentChangeItem.id) {
        goods[i].number = this.data.currentChangeItem.number;
        break;
      }
    }
    this.setData({
      showChangeNumView: false,
      goods: goods
    });
    this.refreshFormatValue();
  },
  addChangeNum: function () {
    this.data.currentChangeItem.number++;
    var mudDisabled = this.data.mudDisabled;
    if (this.data.currentChangeItem.number > 1) {
      mudDisabled = false;
    }
    this.setData({
      currentChangeItem: this.data.currentChangeItem,
      mudDisabled: mudDisabled
    });
  },
  mudChangeNum: function () {
    this.data.currentChangeItem.number--;
    var mudDisabled = this.data.mudDisabled;
    if (this.data.currentChangeItem.number < 2) {
      mudDisabled = true;
    }
    this.setData({
      currentChangeItem: this.data.currentChangeItem,
      mudDisabled: mudDisabled
    });
  },
  delChangeNum: function () {
    var goods = this.data.goods;
    for (var i in goods) {
      if (goods[i].id == this.data.currentChangeItem.id) {
        goods.splice(i, 1);
        return;
      }
    }
  },
  /*选择付款方式*/
  selectMethod: function (e) {
    var payMethod = e.currentTarget.dataset.index;
    this.setData({
      payMethod: payMethod
    });
  },
  /*键入数字*/
  inputNumber: function (e) {
    var num = e.currentTarget.dataset.index;
    var receipts = this.data.receipts;
    if (num == "rm") {
      if (receipts.length > 0) {
        receipts = receipts.substring(0, receipts.length - 1)
      }
    } else if (num == ".") {
      if (receipts.length == 0) {
        receipts += "0."
      } else if (receipts.indexOf(".") < 1) {
        receipts += "."
      }
    } else {
      receipts += num;
    }
    var receiptsFormat = parseInt(receipts);
    var giveChangeValue = 0;
    if (receiptsFormat != null && receipts != "") {
      giveChangeValue = receiptsFormat - this.data.totalAmount.value;
    }
    var giveChange = {
      value: giveChangeValue,
      format: utils.outputmoney(giveChangeValue)
    };
    this.setData({
      receipts: receipts,
      giveChange: giveChange
    });
  },
  confirmSettle: function () {
    var page = this;
    var req = {
      order: {
        totalPrice: this.data.totalAmount.value,
        receipts: this.data.receipts,
        giveChange: this.data.giveChange.value,
        payMethod: this.data.payMethod,
        shopId: wx.getStorageSync("shopId")
      },
      orderItems: []
    };
    var goods = this.data.goods;
    for (var i in goods) {
      var orderItem = {
        totalPrice: goods[i].amount,
        number: goods[i].number,
        goodId: goods[i].id
      };
      req.orderItems.push(orderItem);
    }
    httpClient.post("/order/add", req, function (result) {
      wx.showModal({
        title: '结算成功',
        cancelText: '返回',
        confirmText: '继续收银',
        success: function (res) {
          if (res.confirm) {
            page.refreshPage();
          } else if (res.cancel) {
            wx.navigateBack();
          }
        }
      });
    })
  },
  cancelSettle: function () {
    this.setData({
      showPayView: false,
      receipts: "",
      giveChange: {
        format: "0.00",
        value: 0
      }
    })
  },
  getGoodInfoFromSnap: function (goodCode) {
    var goodsSnap = wx.getStorageSync("goodsSnap");
    if (goodsSnap != null) {
      for (var i in goodsSnap) {
        if (goodCode == goodsSnap[i].code) {
          return goodsSnap[i];
        }
      }
    }
    return null;
  }
})